package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    //微信登录服务接口地址!!
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    //登录参数封装
    private Map<String,String> paramMap(UserLoginDTO userLoginDTO){
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        return paramMap;
    }
    /**
     * 微信用户登录
     * @param userLoginDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口，获取当前微信用户的openid
        String json = null;
        //可能会有登录不上去的情况 所以这里需要try catch
        try {
           json = HttpClientUtil.doGet(WX_LOGIN,paramMap(userLoginDTO));
        }catch (Exception e){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        log.info("调用微信接口获取当前微信用户的openid，参数：{}，返回结果：{}",paramMap(userLoginDTO),json);
        //解析json字符串为JSONObject对象
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        // 判断openid是否为空
        if(openid==null||openid.isEmpty()){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户
        User user = userMapper.queryByOpenid(openid);
        //TODO 这里需要后期完善 微信<小程序>个体用户是无法获取用户信息的 (后期这里直接推送builder字段就行了Mapper层里面已经写好了)(但是在这之前的数据可能存储为Null记得处理)
        if(user==null){
            //新用户，自动注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            int result = userMapper.insertUser(user);
            if(result == StatusConstant.RETURN0){
                throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
            }
        }
        return user;
    }
}
